package com.ybkj.daijia.server.event.listener.zhuanxian;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.PushData;
import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.gexin.GeTuiMember;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.amqp.PushMessage;
import com.ybkj.daijia.server.event.model.zhuanxian.ZhuanxianOrderCancelEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuanxian.Order;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class ZhuanxianOrderCancelEventListener implements
    ApplicationListener<ZhuanxianOrderCancelEvent> {

    private static final Logger logger = LoggerFactory
        .getLogger(ZhuanxianOrderCancelEventListener.class);

    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SmsService smsService;

    @Override
    @Async
    public void onApplicationEvent(ZhuanxianOrderCancelEvent event) {
        Long orderId = (Long) event.getSource();
        Long employId = event.getEmployId();
        String from = event.getFrom();

        Order order = zhuanxianService.findOne(orderId);
        Driver driver = driverService.findOne(employId);

        logger.debug("order zhuanxianCancel event:{}", order.getOrderNo());

        if (null != driver) {
            List<Order> activedList = zhuanxianService.findActivedOrdersByDriver(driver.getId());
            long pai = 0;
            long jie = 0;
            long arrive = 0;
            long busy = 0;
            if (!CollectionUtils.isEmpty(activedList)) {
                for (Order activedOrder : activedList) {
                    if (!activedOrder.getId().equals(order.getId())) {
                        if (activedOrder.getStatus().equals(Order.ORDER_STATUS_PAIDAN)) {
                            ++pai;
                        } else if (activedOrder.getStatus().equals(Order.ORDER_STATUS_JIEDAN)) {
                            ++jie;
                        } else if (activedOrder.getStatus().equals(Order.ORDER_STATUS_ARRIVE)) {
                            ++arrive;
                        } else if (activedOrder.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                            ++busy;
                        }
                    }
                }
            }
            if (busy > 0 || arrive > 0 || jie > 0) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService.updateStatusAndJobStatus(Driver.DRIVER_BUSY,
                        Driver.DRIVER_JOBSTATUS_ZHUANXIAN, driver.getId());
                }
            } else if (pai > 0) {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService.updateStatusAndJobStatus(Driver.DRIVER_APPLY_ORDER,
                        Driver.DRIVER_JOBSTATUS_ZHUANXIAN, driver.getId());
                }
            } else {
                if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                    driverService
                        .updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
                }
            }
        }

        if (null != driver) {
            if (!from.equals(PushMessage.FROM_EMPLOY)) {
                try {
                    //发送设备推送
                    PushDataV4 pushDataV4 = new PushDataV4();
                    pushDataV4.setCode("0X05");
                    pushDataV4.setData(order.getId());
                    pushDataV4.setType("0X04");
                    Map<String, String> extra = new HashMap<String, String>();
                    extra.put("content", "您的工单被销单了,单号:" + order.getOrderNo());
                    pushDataV4.setExtra(extra);

                    boolean getuiOnline = false;
                    if (StringUtils.isNotBlank(driver.getUserID())) {
                        getuiOnline = GeTuiEmployV4
                            .getClientOnline(driver.getUserID(), settingUtils.get());
                    }

                    if (getuiOnline) {
                        GeTuiEmployV4.push(driver, pushDataV4, settingUtils.get());
                    } else {
                        if (StringUtils.isNotBlank(driver.getRegistrationId())) {
                            JiGuangEmployV4.push(driver, pushDataV4, settingUtils.get());
                        }
                    }

                } catch (IOException e) {
                    logger.debug("push error : " + e.getMessage());
                }
            }
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        //给客户推送
        if (null != passenger) {
            if (!from.equals(PushMessage.FROM_PASSENGER)) {
                passenger.setCid(memberService.findCid(passenger.getId()));
                if (StringUtils.isNotBlank(passenger.getCid())) {
                    try {
                        //发送设备推送
                        PushData pushData = new PushData();
                        pushData.setType("CANCEL_ORDER_ZHUANXIAN");
                        pushData.setTitle("城际专线销单");
                        pushData.setDescription("您的城际专线定单已被销单,单号:" + order.getOrderNo());
                        pushData.setData(order.getId());

                        GeTuiMember.push(passenger, pushData, settingUtils.get());
                    } catch (IOException e) {
                        logger.debug("push error : " + e.getMessage());
                    }
                }
            }
        }

        if (null != driver) {
            Company main = companyService.getMain();
            Setting setting = settingUtils.get();
            Company driverCompany = companyService.findOne(driver.getCompanyId());
            Company finalCompany = driverCompany;
            if (!main.getId().equals(driverCompany.getId()) && setting.isSmsMainCompany()) {
                finalCompany = main;
            }

            try {
                SmsTemplet templet = smsService
                    .findByAlias(driver.getCompanyId(), SmsType.cancelOrder);
                if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                    //smsService.sendSms(driver.getPhone(),"cancelZhuanxianOrder", "{\"订单号\":\""+order.getOrderNo()+"\"}",finalCompany.getId(), 0, finalCompany.getSignName());
                    //短信发送（改）
                    JSONObject smsParam = new JSONObject();
                    smsParam.put("order", order.getOrderNo());
                    smsService.sendSms(driver.getPhone(), templet.getTemplateId(),
                        smsParam.toJSONString(), finalCompany.getId(), 0,
                        finalCompany.getSignName());
                }
            } catch (Exception e) {
                logger.error("城际专线销单短信  发送短信发生异常：{}", e.getMessage());
            }
        }


    }


}
